<?php
/**
 * 商品控制器
 */
namespace app\index\controller;
use app\index\controller\Common;
class Goods extends Common{

    /**
     * 商品详情页
     */
    public function goods( $gid = 0 ){

        // 获取商品信息
        $id = input('id')+0;
        $gModel = db('goods as g');
        if( $gid ){

            $id = $gid + 0;

        }

        $good = $gModel->join('jd_goods_info gi','g.gid = gi.gid','LEFT')->where( ['is_on_sale'=>1,'is_delete'=>0,'g.gid'=>$id] )->find();
        ;
        if( $good ){

            // 获取商品相册
            $pics = db('pics')->where('gid','=',$id)->select();

            // 获取货品属性值
            $info = db('goods_attrs ga')->field('ga.*,a.attr_name')->join('jd_attrs a','ga.aid = a.aid','LEFT')->where(['gid'=>$id,'attr_type'=>1])->order('a.sort,ga.id')->select();
            
            // 拼凑货品属性信息
            $attrValues = [];
            foreach ($info as $k => $v) {
                
                //如果存在该属性信息
                if( isset( $attrValues[ $v['aid'] ] ) ) {

                    //如果值不存在
                    if( !in_array($v['attr_value'], $attrValues[ $v['aid'] ]['attr_value']) ) {

                        //将值加入到数组中
                        $attrValues[ $v['aid'] ]['attr_value'][$v['id']] = $v['attr_value'];

                    }

                }else {

                    //属性名
                    $attrValues[ $v['aid'] ]['attr_name'] = $v['attr_name'];

                    //属性值
                    $attrValues[ $v['aid'] ]['attr_value'][$v['id']] = $v['attr_value'];
                    
                }
                
            }
           
            // 获取商品属性
            $goodsAttrs = db('goods_attrs as ga')->field('attr_name,ga.attr_value')->join('jd_attrs a','ga.aid = a.aid','LEFT')->where(['a.attr_type'=>0,'gid'=>$id])->order('a.sort,a.aid')->select();

            // 处理商品价格
            // 有促销的价格就为促销价
            // if($product){
            //     $good["shop_price"] = $product['product_price'];
            // }
            // 
            if($good["is_promote"]== 1 && $good["promote_start_time"] < time() && $good["promote_end_time"] > time() ){ 

                $good["price"] = $good["promote_price"];

            }else if( session('level') ){ 

                $price = db("member_price")->where(["gid" => $good["gid"],"lid" => session('level')])->value("member_price");

                if( $price >0  ){ // 会员价格大于0就按照会员价格

                    $good["price"] = $price; 

                }else if( $price == 0  ){ // 会员价格等于0就按照折扣率算

                    $level = config("member.level");
                    $rate = $level[session('level')][2]/100;
                    $good["price"] = number_format( round( $good["shop_price"] * $rate ), 2); 

                }else{ //否则就按照本店家
                    
                    $good["price"] = $good["shop_price"];

                } 

            }else{ //否则就按照本店家
                $good["price"] = $good["shop_price"];

            } 

            // 更新浏览次数
            $gModel->where('gid','=',$id)->setInc('click');

            // 获取相关分类
            $catModel = db('category');
            $catPid = $catModel->where('cid',$good["cid"])->value('parent_id');
            $extcIds = db('goods_category')->where('gid',$good["gid"])->column('cid');
            $connectCats = $catModel->field('cid,cat_name')->where("parent_id",$catPid )->whereor( ['cid'=>["in",$extcIds] ] )->select();
            
            // 同类品牌
            $catIds = $extcIds;
            $catIds[] = $good["cid"];
            $likeGids = $gModel->where("cid",'in',$catIds )->column('gid'); 
            $model = new \app\index\model\Goods();
            $brands = $model->getLikeBrands( $likeGids );
            
            // 面包屑导航
            $cats = $catModel->field("cid,parent_id,cat_name")->select();
            $catNavs = $model->getNav( $cats, $good["cid"] );
            $catNavs = array_reverse($catNavs);
            
            // // 添加到最近浏览商品
            // $model->addRecentviewedGoods( $id );

            // // 获取最近浏览商品
            // $recentViews = $model->getRecentviewedGoods();
            
            // 设置页面信息
            $this->setPageMsg( $good['goods_name'].'-商品详情页', $good['seo_keyword'], $good['seo_desc'], ['goods','common','bottomnav','jqzoom'], ['goods','jqzoom-core'] );
            
        	//分配变量
            $this->assign('good',$good);
            //$this->assign('commentMan',11);
            $this->assign('pics',$pics);
           // $this->assign('product',$product);
            $this->assign('attrValues',$attrValues);
            //$this->assign('attrSelects',$attrSelects);
            $this->assign('goodsAttrs',$goodsAttrs);
            //$this->assign('impressions',$impressions);
            //$this->assign('comments',$comments);
            //$this->assign('commentRate',$commentRate);
            $this->assign('connectCats',$connectCats);
            $this->assign('brands',$brands);
            $this->assign('catNavs',$catNavs);
            // $this->assign('recentViews',$recentViews);
            $this->assign('goodId',$id);

            //展示视图
    		$html =  $this->fetch('goods');

            if( !is_dir('./goods') ){

                mkdir('./goods',0777);

            }
            
            if( file_put_contents( config('good_cache_dir').'/'.$id.'.html', $html) ){

                $url = $id.'.html';

                // 商品页静态化
                $gModel->strict(true)->where('gid',$id)->update(['static_url'=>$url]);

                // 添加商品
                if( input('type') == 'add' ){

                    $this->success( '添加成功！' ,url('admin/goods/lst') );

                }
                // 修改商品
                else if( input('type') == 'edit' ){

                    $this->success( '修改成功！' ,url('admin/goods/lst') );

                }
                
            }

        }else{

            return false;

        }
    }

    /**
     * 商品列表页
     */
    public function category(){

        // 获取信息
        $id = input('id')+0;

        // 获取分类信息
        $category = db('category')->where('cid','=',$id)->find();

        if( !$category && !input('keyword') ) 
            $this->error("请输入关键字或选择商品分类");

        
        // 获取过滤商品信息
        $gModel = new \app\index\model\Goods();
        $data = $gModel->getFilterGoods($id);

        // 是否存在分类
        if( $category ){

            // 获取相关分类
            $categorys = $gModel->getConnectCats($id);

            // 获取面包屑导航
            $cats = db('category')->field("cid,cat_name,parent_id")->select();
            $navs = array_reverse( $gModel->getNav($cats,$id) );           
            
        }else{

            $categorys = [];
            $navs = [];

        }

        // 设置页面信息
        $this->setPageMsg( $category['cat_name'].'-商品列表页', $category['seo_keyword'], $category['seo_desc'], ['list','common','bottomnav'], ['list'] );
        
        //分配变量
        $this->assign('goods',$data['goods']);
        $this->assign('brands',$data['brands']);
        $this->assign('priceRange',$data['priceRange']);
        $this->assign('attrs',$data['attrs']);
        $this->assign('sortBtnLinks',$data['sortBtnLinks']);
        $this->assign('categorys',$categorys);
        $this->assign('navs',$navs);

        //展示视图
        return $this->fetch();

    }

    /**
     * 异步检查货品
     */
    public function checkProduct(){

        // 安全处理 
        if( !request()->isAjax() ){

            $this->error('您访问的页面不存在！');

        }

        // 接收信息
        $gid = input('id')+0;
        $attrIds = input('attrIds');
        $ids = [];

        // 获取商品下的货品
        $data = db('product')->where('gid','=',$gid)->select(); 

        // 搜索符合条件的货品
        if( !empty($data) ){

            $products = [];
            foreach ($data as $v) {

                if( false !== strpos(','.$v['attr_list'].',', ','.$attrIds.',') ) {

                    $products[] = $v;
                    $ids = array_merge( $ids, explode(',', $v['attr_list']) );
                }
                
            }

            $ids = array_unique($ids);

            // 获取商品
            $good = db('goods')->field('is_promote,promote_start_time,promote_end_time,promote_price')->where('gid','=',$gid)->find();

            // 处理价格
            if($good["is_promote"]== 1 && $good["promote_start_time"] < time() && $good["promote_end_time"] > time() ){ 

               $price = $good["promote_price"];

            }else if( session('level') ){ 
                
                $mprice = db("member_price")->where(["gid" => $gid,"lid" => session('level')])->value("member_price");

                if( $mprice >0  ){ // 会员价格大于0就按照会员价格

                   $price = $mprice; 

                }else if( $mprice == 0  ){ // 会员价格等于0就按照折扣率算

                    $level = config("member.level");
                    $rate = $level[session('level')][2]/100;
                    $price = number_format( round( $products[0]['product_price'] * $rate ), 2,'.',''); 

                }else{ //否则就按照本店家
                    
                   $price = $products[0]['product_price'];

                } 

            }else{ //否则就按照本店家
               $price = $products[0]['product_price'];

            } 

            echo json_encode( ['status'=>true , 'msg'=>$products, 'ids'=>$ids, 'price'=>$price] );

        }else {
            echo json_encode( ['status'=>false , 'msg'=>'没有货品或查询出错！'] );
        }

    }

    /**
     * 后台清除缓存功能
     * @return void
     */
    public function deleteCache(){
        
        // 删除目录
        $this->deleteDir( config('good_cache_dir') );

        // 获取商品id
        $gids = db("goods")->where(['is_on_sale'=>1,'is_delete'=>0])->column("gid");

        // 重新生成商品静态页
        foreach ( $gids as $v ) {
            
            $this->goods($v);
            
        }

        // 跳转会后台首页
        $this->success( '清除缓存成功！',url('admin/index/main') );

    }

    /**
     * 递归删除目录 
     * @param  [type] $path [description]
     * @return [type]       [description]
     */
    public function deleteDir( $path ){
        
        // 检测是不是一个文件
        if( is_file( $path ) ){
            
            // 删除文件
            @unlink( $path );

        }else if( is_dir( $path ) ){

            // 如果是目录，就打开这个目录
            $dir = opendir( $path );

            // 循环读取目录
            while( $file = readdir( $dir ) ){
                
                // 跳过'.'和'..'目录
                if( $file != '.' && $file != '..' ){
                    
                    // 递归调用
                    $this->deleteDir( $path.'/'.$file );

                }

            }
            
            // 关闭目录资源 
            closedir($dir); 

            // 最后删除目录
            rmdir( $path );

        }

    }

    /**
     * 添加最近浏览商品
     */
    public function addRecentviewedGoods(){

        $gid = input('id')+0;


        // 实例化模型
        $model = new \app\index\model\Goods();
        
        // 添加到最近浏览商品
        if( $model->addRecentviewedGoods( $gid ) ){

            // 获取最近浏览商品
            $recentViews = $model->getRecentviewedGoods();

            echo json_encode(['status'=>true,'msg'=>$recentViews]);

        }else{

            echo json_encode(['status'=>false,'msg'=>'添加最新浏览失败！']);

        }

    }

}
